<?php

namespace app\admin\model;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsResponse;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use think\exception\ValidateException;

class Alibaba
{
    /**
     * 使用AK&SK初始化账号Client
     * @return Dysmsapi Client
     */
    public static function createClient(): Dysmsapi
    {
        $accessKeyId = get_sys_config('aliyun_key');
        $accessKeySecret = get_sys_config('aliyun_secret');
        $config = new Config([
            // 您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * @param string[] $args
     * @return SendSmsResponse
     */
    public static function send(array $args): SendSmsResponse
    {
        $sign = get_sys_config('aliyun_sign');
        $template = get_sys_config('aliyun_template');
        $client = self::createClient();
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $args['mobile'],
            "signName" => $sign,
            "templateCode" => $template,
            "templateParam" => json_encode($args['data'])
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            return $client->sendSmsWithOptions($sendSmsRequest, $runtime);
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            throw new ValidateException($error->message);
        }
    }
}